package com.microframework.boot.visual.controller;

import java.sql.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.microframework.base.core.datasource.annotation.Tx;
import com.microframework.base.core.util.SecurityUtils;
import com.microframework.base.core.util.UuidUtil;
import com.microframework.base.web.page.PageQuery;
import com.microframework.base.web.resp.R;
import com.microframework.boot.fs.service.IMinioService;
import com.microframework.boot.visual.model.domain.ComponentLibrary;
import com.microframework.boot.visual.service.IComponentLibrary;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@RequestMapping("/visual/component/library")
@Tag(name = "组件库管理", description = "可视化设计器组件库接口管理相关接口")
public class ComponentLibraryController {

	@Autowired
	private IComponentLibrary componentLibraryService;

	@Autowired
	private IMinioService minioService;

	private final String BUCKET_NAME = "visual";

	@PostMapping("/pages")
	@Operation(summary = "分页查询组件列表", description = "分页查询组件数据")
	public R<Page<ComponentLibrary>> pages(@RequestBody PageQuery<ComponentLibrary> pageQuery) {
		return R.ok(componentLibraryService.pages(pageQuery));
	}

	@Operation(summary = "保存组件")
	@Parameters({ @Parameter(name = "thumbnailFile", description = "缩略图", required = false),
			@Parameter(name = "componentLibrary", description = "组件", required = true) })
	@PostMapping("/save")
	@Tx
	public R<ComponentLibrary> save(HttpServletRequest request, MultipartFile thumbnailFile,
			ComponentLibrary componentLibrary) {
		try {
			if (StrKit.notBlank(componentLibrary.getId())) {
				componentLibrary.setModifyTime(new Date(System.currentTimeMillis()));
				componentLibrary.setModifyUserId(SecurityUtils.getUserId());
				if (componentLibrary.update()) {
					if (thumbnailFile != null) {
						String path = minioService.uploadFile(BUCKET_NAME, thumbnailFile, componentLibrary.getId());
						componentLibrary.setThumbnail(path+'.'+minioService.getFileExtension(thumbnailFile));
						componentLibrary.update();
					}
					return R.ok(componentLibrary);
				} else {
					return R.fail("更新失败！");
				}
			} else {
				componentLibrary.setId(UuidUtil.getUUID());
				componentLibrary.setCreateTime(new Date(System.currentTimeMillis()));
				componentLibrary.setCreateUserId(SecurityUtils.getUserId());
				if (componentLibrary.save()) {
					if (thumbnailFile != null) {
						String path = minioService.uploadFile(BUCKET_NAME, thumbnailFile, componentLibrary.getId());
						componentLibrary.setThumbnail(path+'.'+minioService.getFileExtension(thumbnailFile));
						componentLibrary.update();
					}
					return R.ok(componentLibrary);
				} else {
					return R.fail("保存失败.");
				}
			}
		} catch (Exception e) {
			return R.fail(e.getMessage());
		}
	}

    @Operation(summary = "获取缩略图")
    @Parameters({@Parameter(name = "thumbnail", description = "缩略图文件名", required = true)})
    @GetMapping("/cover/{thumbnail}")
    public ResponseEntity<InputStreamResource> getThumbnail(
            @PathVariable String thumbnail) {
    	return minioService.getThumbnail(BUCKET_NAME, thumbnail);
    }
    
	@Operation(summary = "删除组件")
	@Parameters({ @Parameter(name = "id", description = "用户id", required = true) })
	@DeleteMapping("/detain/{id}")
	@Tx
	public R<String> deleteUserById(@PathVariable("id") String id) {
		try {
			ComponentLibrary project = new ComponentLibrary();
			project.setId(id);
			project.setIsDel("1");
			if (project.update()) {
				minioService.deleteFile(BUCKET_NAME, id);
				return R.ok("删除成功.");
			} else {
				return R.fail("删除失败.");
			}
		} catch (Exception e) {
			log.error("删除异常:{}", e.getMessage());
			return R.fail(e.getMessage());
		}
	}
	
    
	@Operation(summary = "获取组件")
	@Parameters({ @Parameter(name = "id", description = "组件id", required = true) })
	@GetMapping("/{id}")
	public R<ComponentLibrary> get(@PathVariable("id") String id) {
		try {
			ComponentLibrary componentLibrary = ComponentLibrary.dao.findById(id);
			return R.ok(componentLibrary);
		} catch (Exception e) {
			log.error("获取异常:{}", e.getMessage());
			return R.fail(e.getMessage());
		}
	}

	@PostMapping("/{category}/list")
	@Parameters({ @Parameter(name = "category", description = "组件分类", required = true),
			@Parameter(name = "keywords", description = "关键字", required = false) })
	@Operation(summary = "根据分类获取组件库列表", description = "根据分类获取组件库列表数据")
	public R<List<ComponentLibrary>> getListByCategory(@PathVariable("category") String category,
			@RequestParam(name = "keywords", required = false, defaultValue = "") String keywords) {
		return R.ok(componentLibraryService.getListByCategory(category, keywords));
	}

}
